package com.example.xiaohu.modules.controller;

import com.example.xiaohu.modules.entity.FileStorage;
import com.example.xiaohu.modules.service.FileStorageService;
import com.example.xiaohu.common.Result;
import com.example.xiaohu.utils.CommonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/sys/file")
@Api(value="文件上传",tags="文件上传")
public class FileStorageController {

    @Autowired
    private FileStorageService fileStorageService;

    @ApiOperation("上传文件")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Result uploadFile(MultipartFile file,String uploadUserName){

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(uploadUserName==null) uploadUserName="未知";
        log.info("==========文件开始上传==========");
        Result result = new Result();
        String uid = CommonUtils.getUid();
        String originalFileName = file.getOriginalFilename();
        String fileUrl = fileStorageService.uploadFile(file,uid);
        fileUrl = fileUrl.split("\\?")[0];
        if(!fileUrl.equals("")) {
            result.setSuccess(true);
            result.setMessage(fileUrl);
        }else {
            result.setSuccess(false);
        }
        FileStorage fileStorage = new FileStorage();
        fileStorage.setId(uid);
        fileStorage.setFileName(originalFileName);
        fileStorage.setFileUrl(fileUrl);
        fileStorage.setUploadUsername(uploadUserName);
        fileStorage.setUploadTime(df.format(new Date()).toString());
        fileStorageService.save(fileStorage);
        return result;
    }

    @ApiOperation("获取文件列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<FileStorage> listFile(){
        List<FileStorage> fileStorageList = fileStorageService.list();
        return  fileStorageList;
    }

    @ApiOperation("删除指定文件")
    @RequestMapping(value="/delete",method = RequestMethod.POST)
    public Result deleteFile(@RequestBody FileStorage fileStorage){
        log.info("删除id为:"+fileStorage.getId()+"");
        fileStorageService.deleteMinioFile(fileStorage);
        fileStorageService.removeById(fileStorage.getId());
        Result result = new Result();
        result.setSuccess(true);
        result.setMessage("删除成功!");
        return result;
    }
}
